package com.tank.control;

import com.net.Client;
import com.net.entity.TankDirChangedMessage;
import com.net.entity.TankStartMovingMessage;
import com.net.entity.TankStopMessage;
import com.tank.entrity.Tank;
import com.tank.model.GameModel;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TankWindowsKeyListener extends KeyAdapter {
    private final Tank tank;

    private boolean KEY_LEFT;
    private boolean KEY_RIGHT;
    private boolean KEY_UP;
    private boolean KEY_DOWN;

    public TankWindowsKeyListener(Tank tank) {
        this.tank = tank;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT:
                KEY_LEFT = true;
                break;
            case KeyEvent.VK_RIGHT:
                KEY_RIGHT = true;
                break;
            case KeyEvent.VK_UP:
                KEY_UP = true;
                break;
            case KeyEvent.VK_DOWN:
                KEY_DOWN = true;
                break;
            case KeyEvent.VK_SPACE:
//                tank.fire();
                tank.handleFireKey();
                break;
            default:break;
        }
        setMainTankDirection();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT:
                KEY_LEFT = false;
                break;
            case KeyEvent.VK_RIGHT:
                KEY_RIGHT = false;
                break;
            case KeyEvent.VK_UP:
                KEY_UP = false;
                break;
            case KeyEvent.VK_DOWN:
                KEY_DOWN = false;
                break;
            default:break;
        }
        setMainTankDirection();
    }

    public void setMainTankDirection() {
        if (!KEY_LEFT & !KEY_RIGHT & !KEY_UP & !KEY_DOWN) {
            tank.setMoving(false);
            Client.INSTANCE.send(new TankStopMessage((Tank) GameModel.INSTANCE.getMainTank()));
        } else {
            tank.setMoving(true);
            if (KEY_LEFT) {
                tank.setDirectionEnum(DirectionEnum.LEFT);
            }
            if (KEY_RIGHT) {
                tank.setDirectionEnum(DirectionEnum.RIGHT);
            }
            if (KEY_UP) {
                tank.setDirectionEnum(DirectionEnum.UP);
            }
            if (KEY_DOWN) {
                tank.setDirectionEnum(DirectionEnum.DOWN);
            }
            if (KEY_LEFT || KEY_DOWN || KEY_RIGHT || KEY_UP) {
                Client.INSTANCE.send(new TankDirChangedMessage((Tank) GameModel.INSTANCE.getMainTank()));
            }
            if (!((Tank) GameModel.INSTANCE.getMainTank()).isMoving()) {
                Client.INSTANCE.send(new TankStartMovingMessage((Tank) GameModel.INSTANCE.getMainTank()));
            }
        }
    }
}
